const express=require('express');
const bodyParse=require('body-parser');
const multer=require('multer');
const cookieParser=require('cookie-parser');
const cookieSession=require('cookie-session')
const consolidate=require('consolidate');
const mysql=require('mysql');
const config=require('./config')

let server=express();
server.listen(config.port);

const db=mysql.createPool({host:config.mysql_host,user:config.mysql_user,password:config.mysql_password,database:config.mysql_dbname,port:config.mysql_port});
server.use((req,res,next)=>{
	res.showError=function(data){
		res.status(data)
		switch(data){
			case 404:
				res.render('404');
				break;
			case 500:
				res.render('500');
				break;
				default:
					res.render('404');
		}
	}
	req.cwd=__dirname;//保存当前目录d:node_an_ju_ke(dirname变量)
	req.db=db;//把db给全局req
	next();
})
//中间件
//普通POST数据
server.use(bodyParse.urlencoded({extended:false}));//解析

//文件POST数据,文件上传
let multerObj=multer({dest:'./upload/'});
server.use(multerObj.any());

//cookie
server.use(cookieParser(require('./serct/cookie_key')));

//session

server.use(cookieSession({
	keys:require('./serct/sess_key')
}));

//模板
server.set('html',consolidate.ejs);
server.set('view engine','ejs');
server.set('views','./template');

//处理请求
server.use('/admin/',require('./routers/admin'));
server.use('/',require('./routers/www'));

//静态
server.use(express.static('./www'));

server.use((req,res)=>{
	res.showError(404);
})